'use strict';

chrome.runtime.onInstalled.addListener(details => {
  console.log('previousVersion', details.previousVersion);
});

chrome.tabs.onUpdated.addListener(tabId => {
  chrome.pageAction.show(tabId);
});

console.log('\'Allo \'Allo! Event Page for Page Action');
var watchTab = 0;
var stack = [];
chrome.webRequest.onBeforeRequest.addListener(
  function(details) {
    if(details.method == 'POST' || details.method == 'post'){
      return {cancel:false}
    }
    if(details.tabId == watchTab){
      if(stack.length){
        if(details.type == 'main_frame'){
          stack = [];
          stack.push(details.url);
          if(watchTab!=0)
            console.log('}}}');
          console.log('{{{',details.tabId,details.url,details.type)
        }else{
          if(details.url in stack){
            console.log('reuse',details.tabId,details.url,details.type)
          }else{
            stack.push(details.url);
            console.log(details.tabId,details.url,details.type,details)
          }
        }
      }else{
        if(details.type == 'main_frame'){
          stack.push(details.url);
          if(watchTab!=0)
            console.log('}}}');
          console.log('{{{',details.tabId,details.url,details.type)
        }
      }
    }
    return {cancel: false};
  },
  {urls: ['<all_urls>']},
  ['blocking']);

  
chrome.runtime.onMessage.addListener(
  function(request, sender, sendResponse){
    if(watchTab!=sender.tab.id){
      console.log(sender.tab.id, watchTab);
      watchTab = sender.tab.id;
      stack = [];
      sendResponse({reload:true});
    }
  }
);
